package com.gwz.wxtime.openai.com.theokanning.openai;

import cn.hutool.core.lang.Console;
import okhttp3.OkHttpClient;
import okhttp3.internal.platform.Platform;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.httpclient.DefaultOkHttpClientFactory;
import org.springframework.cloud.commons.httpclient.OkHttpClientFactory;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Configuration("feogmCpmfog")
@EnableFeignClients(basePackages = "com.gwz.wxtime.openai.com.theokanning.openai")
public class Config {
    @Value("${proxy.host}")
    private String proxyHost;
    @Value("${proxy.port}")
    private Integer proxyPort;
    @Value("#{'${proxy.domains}'.split(',')}")
    private Set<String> domainList;

    @Bean
    public OkHttpClientFactory okHttpClientFactory(OkHttpClient.Builder builder) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Console.log("okttp日志","okttp日志 = "+message);
            }
        });
        builder.addInterceptor(loggingInterceptor);
        ProxyOkHttpClientFactory proxyOkHttpClientFactory = new ProxyOkHttpClientFactory(builder);

        return proxyOkHttpClientFactory;
    }

    class ProxyOkHttpClientFactory extends DefaultOkHttpClientFactory {
        public ProxyOkHttpClientFactory(OkHttpClient.Builder builder) {
            super(builder);
            //如果配置文件中的代理信息为null 则该代理ip配置不生效
            if(proxyHost!=null&&proxyPort!=null&&domainList!=null) {
                Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
                List<Proxy> proxyList = new ArrayList<>(1);
                proxyList.add(proxy);
                builder.proxySelector(new ProxySelector() {
                    @Override
                    public List<Proxy> select(URI uri) {
                        if (uri == null || !domainList.contains(uri.getHost())) {
                            return Collections.singletonList(Proxy.NO_PROXY);
                        }

                        return proxyList;
                    }

                    @Override
                    public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                    }
                });
            }
        }
    }
}
